import java.awt.*;
import java.awt.image.*;
import java.io.*;

import javax.imageio.ImageIO;


public class PngDecrypter {

  public static void main(final String[] args) throws IOException {
    if (args.length != 2) {
      System.err.println("Usage: java PngDecrypter <input> <output>");
      System.exit(1);
    }
    final Image image = ImageIO.read(new File(args[0]));
    
    final int width = image.getWidth(null);
    final int height = image.getHeight(null);
    
    final BufferedImage buffer = new BufferedImage(width,
            height, BufferedImage.TYPE_BYTE_GRAY);
    
    final Graphics g = buffer.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    
    WritableRaster raster = buffer.getRaster();
    
    for (int y = 0; y < height; y++) {
      //extract line
      final int[] line = raster.getPixels(0, y, width, 1, (int[]) null);
      
      int shift = 0;
      //line ends with \0
      if (line[width - 1] == 0) {
        //search shift from the beginning
        while (line[shift] == 0) {
          shift++;
        }
        
        //otherwise look for \0 from the end
      } else {
        shift = width - 1;
        while (line[shift] != 0) {
          shift--;
        }
        shift++;
      }
      
      //now copy the line to a new array
      final int[] newLine = new int[width];
      //shifting the line to the correct position
      System.arraycopy(line, shift, newLine, 0, width - shift);
      if (shift > 10) {
        System.arraycopy(line, 0, newLine, width - shift, shift);
      }
      //and store the line in the image again
      raster.setPixels(0, y, width, 1, newLine);
    }
    
    ImageIO.write(buffer, "png", new File(args[1]));
  }
}
